package com.car.datalayer.http;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map.Entry;

public class CHttpResponse implements Serializable{
	private static final long serialVersionUID = 1L;
	
	/**
	 *  HTTP状态返回码
	 */
	private int statusCode = 0;
	/**
	 *  头部信息
	 */
	private HashMap<String, String> headers;
	/**
	 * 返回的内容
	 */
	private byte[] responseBody;
	
	public CHttpResponse(int statusCode){
		this.statusCode = statusCode;
	}
	
	public int getStatusCode() {
		return statusCode;
	}
	public void setStatusCode(int statusCode) {
		this.statusCode = statusCode;
	}
	
	public String GetHeader(String key){
		if(headers == null ||
		   !headers.containsKey(key)){
			return "";
		}
		return headers.get(key);
	}
	
	public void SetHeader(String key, String value){
		if(headers == null){
			headers = new HashMap<String, String>();
		}
		headers.put(key, value);
	}
	
	public byte[] getResponseBody() {
		if(responseBody == null){
			return new byte[0];
		}
		return responseBody;
	}
	public void setResponseBody(byte[] responseBody) {
		this.responseBody = responseBody;
	}
	
	@Override
	public String toString(){
		StringBuffer buffer = new StringBuffer(256);
		buffer.append("{\n" +
				"statusCode=" + statusCode + "\n");
		if(headers != null){
			for(Entry<String, String> header: headers.entrySet()){
				buffer.append(header.getKey() + "=" + header.getValue() + "\n");
			}
		}
		if(responseBody != null){
			try {
				buffer.append(new String(responseBody, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		buffer.append("}\n");
		return buffer.toString();
	}
}
